package lion.json.handlers;

import java.io.IOException;
import java.io.Writer;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;

import lion.dev.lang.BeanUtil;
import lion.json.IJsonHandler;
import lion.json.Json;

/**
 * static field will be skiped<br/>
 * if the object has method toJSON,handler will use it instead
 *
 * @author lion
 * @mail hl_0074@sina.com
 * @date 2011-9-27
 */
public class ObjectHandler implements IJsonHandler {

	@Override
	public void handle(Object o, Writer writer) throws IOException {

		BeanUtil bu = new BeanUtil(o);
		if (bu.hasMethod("toJSON")) {
			writer.write((String) bu.exec("toJSON"));
			return;
		}

		writer.write("{");
		boolean added = false;
		for (Field f : o.getClass().getDeclaredFields()) {
			f.setAccessible(true);
			if (Modifier.isStatic(f.getModifiers())) {
				continue;
			}
			Object value = null;
			try {
				value = f.get(o);
			} catch (Exception e1) {
			}
			if (value == o) {
				continue;
			}

			// 内部类中的自身实例引用要滤掉
			if (f.getName().startsWith("this$") && f.getType() == o.getClass().getDeclaringClass()) {
				continue;
			}

			if (added) {
				writer.write(",");
			}
			try {
				// 内部类中的父类实例引用要过滤掉

				writer.write("\"" + f.getName() + "\":");
				Json.toJson(value, writer);
			} catch (Exception e) {
				throw new IOException(e);
			}
			added = true;
		}
		writer.write("}");
	}
}
